/**
 * Bakalarska prace - Inteligentni budik
 * @package sleepCatcher
 * @file FormSessionDelete.cpp
 * @author Jan Pesava - xpesav00
 * @email xpesav00@stud.fit.vutbr.cz
 * @date 24. 12. 2011
 */

#include <FGraphics.h>

#include "forms/FormSessionDelete.h"
#include "SCFormManager.h"
#include "models/SCSession.h"
#include "models/SCHelpers.h"
#include "SCDatabase.h"
#include "models/SCDataModification.h"
#include "SCTranslator.h"

using namespace Osp::Graphics;


FormSessionDelete::FormSessionDelete()
{
}

FormSessionDelete::~FormSessionDelete()
{
}

bool
FormSessionDelete::Initialize()
{
	Construct(L"IDF_SESSION_DELETE");
	return true;
}

result
FormSessionDelete::OnInitializing(void)
{
	result r = E_SUCCESS;

	//load Sessions
	this->LoadAllSessions();

	//init form
	this->pSessionsListView = static_cast<ListView*>(GetControl("IDC_LISTVIEW_SESSION_DELETE"));
	this->pSessionsListView->SetItemProvider(*this);
	this->pSessionsListView->SetTextOfEmptyList(SCTranslator::GetText("IDS_SESSIONDELETE_EMPTY"));
	this->pSessionsListView->Draw();

	//language
	this->SetTitleText(SCTranslator::GetText("IDS_SESSIONDELETE_TITLE"));

	//set Footer
	Footer* pFooter = GetFooter();
	pFooter->SetStyle(FOOTER_STYLE_BUTTON_TEXT);
	pFooter->AddActionEventListener(*this);

	FooterItem* pDeleteItem = new FooterItem();
	pDeleteItem->Construct(IDA_SESSION_DELETE);
	pDeleteItem->SetText(SCTranslator::GetText("IDS_GENERAL_DELETE"));

	FooterItem* pBackItem = new FooterItem();
	pBackItem->Construct(IDA_SESSION_BACK);
	pBackItem->SetText(SCTranslator::GetText("IDS_GENERAL_BACK"));

	pFooter->AddItem(*pDeleteItem);
	pFooter->AddItem(*pBackItem);

	delete pDeleteItem;
	delete pBackItem;

	return r;
}

result
FormSessionDelete::OnTerminating(void)
{
	result r = E_SUCCESS;
	return r;
}

void
FormSessionDelete::OnActionPerformed(const Osp::Ui::Control& source, int actionId)
{
	switch(actionId)
	{
		case IDA_SESSION_BACK:
			SCFormManager::SwitchToForm(SCFormManager::IDF_SESSIONS, false, null, SCFormManager::NO_SLIDE);
			break;
		case IDA_SESSION_DELETE:
			this->DeleteSessions();
			break;
	}
}

void
FormSessionDelete::OnListViewContextItemStateChanged (Osp::Ui::Controls::ListView &listView, int index, int elementId, Osp::Ui::Controls::ListContextItemStatus status)
{
}

void
FormSessionDelete::OnListViewItemLongPressed (Osp::Ui::Controls::ListView &listView, int index, int elementId, bool &invokeListViewItemCallback)
{
}

void
FormSessionDelete::OnListViewItemStateChanged (Osp::Ui::Controls::ListView &listView, int index, int elementId, Osp::Ui::Controls::ListItemStatus status)
{
}

void
FormSessionDelete::OnListViewItemSwept (Osp::Ui::Controls::ListView &listView, int index, Osp::Ui::Controls::SweepDirection direction)
{
}

Osp::Ui::Controls::ListItemBase*
FormSessionDelete::CreateItem(int index, int itemWidth)
{
	CustomItem* pCustomItem = NULL;
	IEnumerator *pEnum = NULL;
	SCSession *pSession;
	int titleSize = 20;
	Color *pColor;
	Bitmap* pGraph;
	pColor = new Color(193, 228, 247);

	if(this->pSessionsList->GetCount() > 0)
	{
		pEnum = this->pSessionsList->GetEnumeratorN();
		pSession = static_cast<SCSession*>(this->pSessionsList->GetAt(index));

		pCustomItem = new CustomItem();
		pCustomItem->Construct(Dimension(itemWidth,150), LIST_ANNEX_STYLE_RADIO);

		// Title,from - to
		String sampleCountStr;
		sampleCountStr.Append(pSession->GetSamplesCount());
		String dateFrom = SCHelpers::ConvertDateTimeToString(pSession->GetStartDate(), "dd.MM.");
		String dateTo = SCHelpers::ConvertDateTimeToString(pSession->GetStopDate(), "dd.MM.");
		String titleStr = SCTranslator::GetText("IDS_SESSION_SLEEPRECORD")+ ": " + dateFrom + " - " + dateTo + "," + SCTranslator::GetText("IDS_SESSION_SAMPLESCOUNT") + ": " + sampleCountStr;
		pCustomItem->AddElement(Rectangle(0,0,itemWidth - 80,20), 0, titleStr , titleSize, *pColor, Color::COLOR_WHITE, *pColor, true);

		// Set BackgroundImg
		String dstPath = "/Home/Sessions/Graphs/";
		dstPath.Append(pSession->GetId());
		dstPath.Append(".png");
		Image* pImage = new Image();
		pImage->Construct();
		if(File::IsFileExist(dstPath))
		{
			pGraph = pImage->DecodeN(dstPath, BITMAP_PIXEL_FORMAT_RGB565, itemWidth - 80, 130);
		} else {
			pGraph = pImage->DecodeN(L"/Home/Icons/Commons/sleepGraphNoPhoto.png", BITMAP_PIXEL_FORMAT_RGB565, itemWidth - 80, 130);
		}
		pCustomItem->AddElement(Rectangle(0,20,itemWidth - 80, 130), 1, *pGraph, pGraph, pGraph);

		delete pImage;
		delete pEnum;
		delete pGraph;
	} else {
		this->pSessionsListView->SetTextOfEmptyList(SCTranslator::GetText("IDS_ALARMS_NO_ALARMS"));
	}

	delete pColor;

	return pCustomItem;
}

bool
FormSessionDelete::DeleteItem(int index, Osp::Ui::Controls::ListItemBase* pItem, int itemWidth)
{
	delete pItem;
	pItem = NULL;
	return true;
}

int
FormSessionDelete::GetItemCount(void)
{
	if(this->pSessionsList != NULL)
	{
		return this->pSessionsList->GetCount();
	} else {
		return 0;
	}
}

int
FormSessionDelete::GetFormId()
{
	return SCFormManager::IDF_SESSIONS_DELETE;
}

void
FormSessionDelete::LoadAllSessions()
{
	this->pSessionsList = SCSession::GetAllSessions();
}

void
FormSessionDelete::DeleteSessions()
{
	SCSession* pSession;
	int modalResult;
	MessageBox msg;
    int deletedItemCount = 0;
	int sessionItemCount = this->pSessionsList->GetCount();

	// remove checked item
	if(sessionItemCount > 0)
	{
		for(int i = sessionItemCount - 1; i >= 0; i--)
		{
			if(this->pSessionsListView->IsItemChecked(i))
			{
				pSession = static_cast<SCSession*>(this->pSessionsList->GetAt(i));
				SCSession::Delete(pSession->GetId());
				this->pSessionsList->RemoveAt(i, true);
				this->pSessionsListView->RefreshList(i, LIST_REFRESH_TYPE_ITEM_REMOVE);
				deletedItemCount++;

				//cache
				SCDatabase::AddDataModification(SCDatabase::ACTION_DELETE, SCFormManager::IDF_SESSIONS, i);
				SCDatabase::SetReloadSessions(true);
			}
		}
	}

	if(deletedItemCount > 0)
	{
		msg.Construct(SCTranslator::GetText("IDS_GENERAL_NOTICE"), SCTranslator::GetText("IDS_SESSIONDELETE_ITEMSDELETED"), MSGBOX_STYLE_NONE, 1000);
	} else {
		msg.Construct(SCTranslator::GetText("IDS_GENERAL_NOTICE"), SCTranslator::GetText("IDS_SESSIONDELETE_NOITEMSELECTED"), MSGBOX_STYLE_NONE, 1000);
	}

	// show msg
	msg.ShowAndWait(modalResult);
}

void
FormSessionDelete::Update()
{
	this->LoadAllSessions();

	// reload listView
	if(SCDatabase::GetReloadSessionsDelete())
	{
		ArrayList* pDataModificationList = SCDatabase::GetDataModificationList();
		IEnumerator* pEnum = pDataModificationList->GetEnumeratorN();
		SCDataModification* pDataModification;
		ArrayList* pDeletedItems = new ArrayList();

		while(pEnum->MoveNext() == E_SUCCESS)
		{
			pDataModification = static_cast<SCDataModification*>(pEnum->GetCurrent());

			if(pDataModification->GetFormId() == SCFormManager::IDF_SESSIONS_DELETE)
			{
				switch(pDataModification->GetOperationType())
				{
					case SCDatabase::ACTION_ADD:
						this->pSessionsListView->RefreshList(pDataModification->GetItemId(), LIST_REFRESH_TYPE_ITEM_ADD);
						break;
					case SCDatabase::ACTION_MODIFY:
						this->pSessionsListView->RefreshList(pDataModification->GetItemId(), LIST_REFRESH_TYPE_ITEM_MODIFY);
						break;
					case SCDatabase::ACTION_DELETE:
						this->pSessionsListView->RefreshList(pDataModification->GetItemId(), LIST_REFRESH_TYPE_ITEM_REMOVE);
						break;
				}

				pDeletedItems->Add(*pDataModification);
			}
		}

		//delete items
		pDataModificationList->RemoveItems(*pDeletedItems, true);

		//this->pSessionsListView->UpdateList();
		SCDatabase::SetReloadSessionsDelete(false);

		//dealloc
		pDeletedItems->RemoveAll();
		delete pDeletedItems;
		delete pEnum;
	}


	//set all item uncheck
	for(int i = 0; i < this->pSessionsList->GetCount(); i++)
	{
		this->pSessionsListView->SetItemChecked(i, false);
	}

	if(this->pSessionsList->GetCount() > 0)
	{
		this->pSessionsListView->ScrollToItem(0);
	}
}

void
FormSessionDelete::Redraw()
{
	this->Update();
	RequestRedraw(true);
}

